<template>
  <el-dialog
    :title="title"
    :visible.sync="visible"
    width="50%"
    :before-close="handleClose"
    header-btn-text="新增分类"
  >
    <el-form ref="form" :model="form" label-width="80px">
      <el-form-item label="分类" prop="category" :rules="{ required: true, message: '请输入分类'}">
        <div style="width: 40%;">
          <el-input v-model="form.category" placeholder="请输入分类" clearable size="small" />
        </div>
      </el-form-item>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button size="small" @click="handleClose">取 消</el-button>
      <el-button type="primary" size="small" :loading="loading" @click="onSubmit">确 定</el-button>
    </span>
  </el-dialog>
</template>

<script>
import request from '@/utils/request'

export default {
  components: {
    // QuillText
  },
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    title: String,
    defaultValue: {
      type: Object,
      default: () => ({})
    }
  },
  data() {
    return {
      form: {

      },
      loading: false
    }
  },
  watch: {
    defaultValue(val, val2) {
      this.form = val
    }
  },
  methods: {
    onSubmit() {
      this.$refs['form'].validate((valid) => {
        if (valid) {
          // 拆分城市

          this.request(this.form)
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },

    async request(params) {
      try {
        this.loading = true
        await request({
          url: 'system/category',
          method: params.id ? 'put' : 'post',
          data: params
        })
        this.$message({
          message: params.id ? '修改成功' : '添加成功',
          type: 'success',
          duration: 2000,
          onClose: () => {
            this.$emit('add-success')
            this.$refs['form'].resetFields()
            // this.form = { category: '' }
          }
        })
      } catch (error) {
        this.$message({
          message: error,
          type: 'warning'
        })
      } finally {
        this.loading = false
      }
    },
    handleClose() {
      this.$emit('close:drawer', false)
    }
  }
}
</script>

<style scoped>
  .item {
    display: flex;
    justify-content: right;
  }
  .required {
    color: red;
  }
</style>
